<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属机构" prop="tenantId">
        <el-select v-model="queryParams.tenantId" placeholder="请选择机构" clearable filterable>
          <el-option v-for="item in tenantList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券类型" prop="couponType" label-width="100px">
        <el-select v-model="queryParams.couponType" placeholder="请选择类型" clearable filterable>
          <el-option v-for="item in dict.type.coupon_type" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优惠券名称" prop="couponName" label-width="100px">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker clearable
                        v-model="dateRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:coupon:add']"
        >添加优惠券
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs :active-name="activeName" v-model="queryParams.couponState" @tab-click="handleTabClick">
      <el-tab-pane v-for="(item, index) in tabs" :label="item.label" :name="item.name" :key="index"></el-tab-pane>
    </el-tabs>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column label="序号" width="55" align="center">
        <template slot-scope="scope">{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="所属机构" align="center" prop="tenantName"/>
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="券码" align="center" prop="couponId"/>
      <el-table-column label="优惠券名称" align="center" prop="couponName"/>
      <el-table-column label="优惠券面额" align="center" prop="couponDenomination"/>
      <el-table-column label="适用范围" align="center" prop="applyScope">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apply_scope" :value="scope.row.applyScope"/>
        </template>
      </el-table-column>
      <el-table-column label="领取方式" align="center" prop="pickupMethod">
        <template slot-scope="scope">
          <span>{{ scope.row.pickupMethodName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用门槛" align="center" prop="minConsume">
        <template slot-scope="scope">
          <span v-if="scope.row.couponType === '2'">无门槛</span>
          <span v-else>满{{ scope.row.couponThreshold }}可用</span>
        </template>
      </el-table-column>
      <el-table-column label="总数量/剩余数量" align="center" prop="totalCirculation">
        <template slot-scope="scope">
          <span v-if="scope.row.totalCirculation === 0">无限制</span>
          <span v-else>{{ scope.row.totalCirculation }}/{{ scope.row.remainingNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span>至</span>
          <span>{{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="createBy"/>
      <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}:{h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="couponState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_state" :value="scope.row.couponState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleAudit(scope.row)"
            v-hasPermi="['manage:coupon:edit']"
            v-if="scope.row.couponState === '1'"
          >提交审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleDetail(scope.row)"
            v-hasPermi="['manage:coupon:query']"
            v-if="['2', '3', '4', '5', '6'].includes(scope.row.couponState)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:coupon:edit']"
            v-if="scope.row.couponState === '1'"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleEnd(scope.row)"
            v-hasPermi="['manage:coupon:edit']"
            v-if="scope.row.couponState === '3'||scope.row.couponState === '4'"
          >提前结束
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleDelivery(scope.row)"
            v-hasPermi="['manage:coupon:edit']"
            v-if="scope.row.pickupMethod === '4' && (scope.row.couponState === '3'||scope.row.couponState === '4')"
          >派送
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleReSubmit(scope.row)"
            v-hasPermi="['manage:coupon:edit']"
            v-if="scope.row.couponState === '6'"
          >重新提交
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:coupon:remove']"
            v-if="scope.row.couponState === '1' || scope.row.couponState === '6'"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改普通消息推送对话框 -->
    <add :show.sync="open" :data="form" :title="title" @success="getList"/>
    <!-- 详情弹窗 -->
    <detail :show.sync="showDetail" :data="detail" :title="title" @success="getList"/>
    <select-user :show.sync="showSelectUser" @success="handleSelectUserSuccess"
                 :selected-data="[]"></select-user>
  </div>
</template>

<script>
import {listDepartment} from "@/api/sys-enterprise";
import Detail from "./components/detail.vue"
import Add from "./components/add.vue"
import {debounce} from "@/utils";
import {
  appointCoupon,
  deleteCoupon,
  earlyFinishCoupon,
  getCouponDetail,
  getCouponList,
  submitAuditCoupon
} from "@/api/marketing/coupon";
import selectUser from "@/views/marketing/coupon/components/selectUser.vue";

export default {
  name: "coupon",
  dicts: ['apply_scope', 'coupon_state','coupon_type'],
  components: {
    selectUser,
    Detail,
    Add
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 机构列表
      tenantList: [],
      // 当前激活的tab
      activeName: "all",
      // 表格tab
      tabs: [
        {label: '全部', name: 'all'},
        {label: '待提交', name: '1'},
        {label: '待审核', name: '2'},
        {label: '待开始', name: '3'},
        {label: '活动中', name: '4'},
        {label: '已结束', name: '5'},
        {label: '已驳回', name: '6'},
      ],
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 详情弹窗
      showDetail: false,
      showSelectUser: false,
      // 详情数据
      detail: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponState: '', // 优惠券状态
        couponName: '', // 优惠券名称
        createBy: '', // 申请人
        createTime: [], // 申请时间
        tenantId: null // 机构id
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getDepartmentList();
  },
  methods: {
    // 查询机构列表
    getDepartmentList() {
      listDepartment().then(response => {
        this.tenantList = response.data.map(item => {
          return {
            label: item.tenantName,
            value: item.tenantId
          }
        });
      });
    },
    /** 查询普通消息推送列表 */
    getList() {
      this.loading = true;
      getCouponList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleTabClick(tab) {
      this.activeName = tab.name;
      this.queryParams.couponState = tab.name === 'all' ? '' : tab.name;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.couponId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.open = true;
      this.title = "新增优惠券";

      // this.$router.push({path: '/marketing/coupon/add'});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const couponId = row.couponId
      getCouponDetail(couponId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    /** 重新提交按钮操作 */
    handleReSubmit(row) {
      const couponId = row.couponId
      getCouponDetail(couponId).then(response => {
        this.form = response.data;
        this.form['isReSubmit'] = true;
        this.open = true;
        this.title = "重新提交";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      getCouponDetail(row.couponId).then(response => {
        this.detail = response.data;
        this.showDetail = true;
        this.title = "详情";
      });
    },
    /** 提交审核按钮操作 */
    handleAudit(row) {
      const couponIds = row.couponId
      this.$modal.confirm('确定提交审核？', '提示').then(function () {
        return submitAuditCoupon(couponIds);
      }).then((response) => {
        console.log('response', response)
        this.getList();
        this.$modal.msgSuccess(response.msg || "操作成功");
      }).catch(() => {
      });
    },
    /** 提前结束按钮操作 */
    handleEnd(row) {
      const couponIds = row.couponId
      this.$modal.confirm('确定提前结束？', '提示').then(function () {
        return earlyFinishCoupon(couponIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {
      });
    },
    // 派送按钮操作
    handleDelivery(row) {
      this.form = {...row}
      this.showSelectUser = true;
    },
    handleSelectUserSuccess(data) {
      let params = {
        couponId: this.form.couponId,
        couponRecordList: data.map(item => {
          return {
            userId: item.userId,
            userName: item.userName,
            userPhone: item.phonenumber ? item.phonenumber : item.userPhone
          }
        })
      }
      console.log('params', params)
      appointCoupon(params).then(response => {
        this.getList();
        this.showSelectUser = false;
        this.$modal.alert(response.msg || '发送成功');
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponIds = row.couponId || this.ids;
      this.$modal.confirm('确定删除？', '提示').then(function () {
        return deleteCoupon(couponIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    }
  }
};
</script>
